<template>
    <div v-loading="loading" class="console-page">
        <el-form inline :model="searchForm" class="e-page form-item" spellcheck="false" @submit.native.prevent>
            <el-row class="toolbar" ref="el">
                <el-col :span="3" style="padding-right: 5px">
                    <el-input v-model="searchForm.url" placeholder="接口地址,全词匹配" clearable class="input-auto-resize" />
                </el-col>
                <el-col :span="3" style="padding-right: 5px">
                    <el-select v-model="searchForm.status" class="input-auto-resize" clearable placeholder="请选择接口状态">
                        <el-option label="成功" value="1" />
                        <el-option label="失败" value="0" />
                    </el-select>
                </el-col>
                <el-col :span="4" style="padding-right: 5px">
                    <el-date-picker v-model="searchForm.date" type="daterange" unlink-panels range-separator="~"
                        start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts"
                        class="input-auto-resize cursor-pointer" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                        popper-class="poper-auto-reisze" :disabled-date="disabledDate" :cell-class-name="cellClass" />
                </el-col>
                <el-col :span="1"
                    style="padding-right: 5px;max-width: calc(var(--font-size) * 6 + 10px);min-width: calc(var(--font-size) * 6 + 10px)">
                    <el-switch v-model="searchForm.cost" active-value="0" inactive-value="2000" active-text="全部查询"
                        inactive-text="慢查询" inline-prompt class="fit-auto-resize interface-log-switch cursor-pointer">
                    </el-switch>
                </el-col>
                <el-col :span="1" v-if="url === '/interface/log'"
                    style="padding-right: 5px;max-width: calc(var(--font-size) * 6 + 10px);min-width: calc(var(--font-size) * 6 + 10px)">
                    <el-switch v-model="searchForm.apiType" active-value="1" inactive-value="0" active-text="内部接口"
                        inactive-text="开放接口" inline-prompt class="fit-auto-resize interface-log-switch cursor-pointer">
                    </el-switch>
                </el-col>
                <el-col :span="3" style="padding-right: 5px">
                    <el-button type="primary" @click="searchTable" circle :icon="getIcon('search')"
                        :loading="bt_loading" class="button-auto-resize" native-type="submit">
                    </el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" border header-cell-class-name="el-table-header-cell" cell-class-name="el-table-cell"
            class="e-page table-with-pagination" ref="tableRef" highlight-current-row>
            <el-table-column prop="sequence" label="日志编号" :width="fontAutoResize.size_12.value" />
            <el-table-column prop="url" label="请求地址" width="200" />
            <el-table-column prop="method" label="请求方式" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <el-tag :type="scope.row.method.toUpperCase() === 'GET' ? 'success' : 'primary'"
                        class="input-auto-resize">
                        {{ scope.row.method ? scope.row.method.toUpperCase() : '' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="请求状态" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" class="input-auto-resize">
                        {{ scope.row.status === 1 ? "成功" : "失败" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="responseCode" label="状态码" :width="fontAutoResize.size_6.value">
                <template #default="scope">
                    <el-tag :type="scope.row.responseCode === '200' ? 'success' : 'danger'" class="input-auto-resize">
                        {{ scope.row.responseCode }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="params" label="请求参数" min-width="300">
                <template #default="scope">
                    {{ scope.row.params === "{}" ? "" : scope.row.params }}
                </template>
            </el-table-column>
            <el-table-column prop="token" label="IP地址" :width="fontAutoResize.size_10.value">
                <template #default="scope">
                    {{ scope.row.ipInfo ? scope.row.ipInfo.ip : "" }}
                </template>
            </el-table-column>
            <el-table-column prop="token" label="IP属地" :width="fontAutoResize.size_10.value">
                <template #default="scope">
                    {{ getIpAddress(scope.row) }}
                </template>
            </el-table-column>
            <el-table-column prop="token" label="网络运营商" :width="fontAutoResize.size_7.value">
                <template #default="scope">
                    {{
                        scope.row.ipInfo && scope.row.ipInfo.data ? scope.row.ipInfo.data.isp : ""
                    }}
                </template>
            </el-table-column>
            <el-table-column prop="referer" label="请求来源" width="320" />
            <el-table-column prop="startTimestamp" label="请求开始时间" :width="fontAutoResize.size_13.value" />
            <el-table-column prop="endTimestamp" label="请求结束时间" :width="fontAutoResize.size_13.value" />
            <el-table-column prop="cost" label="请求耗时" :width="fontAutoResize.size_7.value">
                <template #default="scope">
                    <el-tag :type="scope.row.cost > 2000 ? 'danger' : 'success'" class="input-auto-resize">
                        {{ scope.row.cost + "ms" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" :width="operationWidth" className="operation-column">
                <template #default="scope">
                    <el-button type="primary" :icon="getIcon('document')" circle class="button-auto-resize"
                        @click="getDocument(scope.row)" />
                </template>
            </el-table-column>
        </el-table>
        <div style="height: 50px;">
            <el-pagination background @size-change="SizeChange" @current-change="CurrentChange"
                :current-page="currentPage" :page-sizes="page_sizes" :page-size="page_size"
                layout="total, sizes, prev, pager, next, jumper" prev-text="<上一页" next-text="下一页>" :total="total"
                class="e-page">
            </el-pagination>
        </div>
        <el-dialog title="返回信息" v-model="dialogVisible" width="50%" class="return-message forbid-select" append-to-body>
            <highlight :code="exception" :language="language" />
        </el-dialog>
    </div>
</template>
<script setup>
import highlight from "@/components/editor/highlight"
import { formatJson, getIpAddress, getIcon } from "@/utils/tools"
import { useElMessage, useSetTableOperationWidth, useRequest } from "@usehook"
import { isArray } from "@vue/shared"
import { fontAutoResize } from "@/utils/setting"

const operationWidth = useSetTableOperationWidth(1)

const props = defineProps({ url: { required: true, type: String, default: '' } })

let tableData = ref([])
let currentPage = $ref(1)
let page_size = $ref(0)
let total = $ref(0)
let dialogVisible = $ref(false)
let searchForm = $ref({
    url: '',
    status: '',
    cost: '0',
    date: '',
    apiType: props.url === '/interface/log' ? "1" : "-1"
})
let language = $ref('')
let loading = $ref(false)
let bt_loading = $ref(false)
let page_sizes = [10, 30, 50, 100, 200]
let exception = $ref("")
let shortcuts = [{
    text: '最近一周',
    value() {
        const end = new Date();
        const start = new Date();
        start.setDate(start.getDate() - 7);
        start.setDate(start.getDate() + 1);
        return [start, end];
    }
}, {
    text: '最近一个月',
    value() {
        const end = new Date();
        const start = new Date();
        start.setMonth(start.getMonth() - 1);
        start.setDate(start.getDate() + 1);
        return [start, end];
    }
}, {
    text: '最近三个月',
    value() {
        const end = new Date();
        const start = new Date();
        start.setMonth(start.getMonth() - 3);
        start.setDate(start.getDate() + 1);
        return [start, end];
    }
}]

const disabledDate = (date) => {
    return date.getTime() > Date.now()
}

const cellClass = (date) => {
    return date.getTime() > Date.now() ? "cursor-default" : "cursor-pointer"
}

const getDocument = (row) => {
    exception = row.status === 1 ? formatJson(row.sketch) : row.fullException;
    dialogVisible = true;
    language = row.status === 1 ? "json" : "java"
}

const getInterfaceLogInfo = (params) => {
    loading = true;
    bt_loading = true;
    useRequest({ url: props.url, ...params }).then(resp => {
        if (resp.status) { //0表示成功，1表示失败
            tableData = resp.data;
            total = resp.totalRecord;
        } else if (resp.message) useElMessage(resp.message);
    }).finally(_ => {
        loading = false;
        bt_loading = false;
    })
}

const searchValue = $computed(() => {
    const { date, ...packageParams } = searchForm
    return { ...packageParams, date: isArray(date) ? date.join(",") : date }
})

const searchTable = () => {
    getInterfaceLogInfo({
        'search': JSON.stringify(searchValue), 'limit': page_size, 'page': 1
    });
    currentPage = 1;
}

const SizeChange = (val) => {
    getInterfaceLogInfo({
        'search': JSON.stringify(searchValue), 'limit': val, 'page': currentPage
    });
    page_size = val;
}

const CurrentChange = (val) => {
    getInterfaceLogInfo({
        'search': JSON.stringify(searchValue), 'limit': page_size, 'page': val
    });
    currentPage = val;
}

onMounted(() => {
    page_size = page_sizes[1];
    searchTable();
})
</script>

<style scoped>
.el-scrollbar__bar.is-vertical>div {
    width: 0;
}
</style>

<style lang="scss">
.return-message .el-dialog__body {
    padding: 2px 5px !important;
    height: 400px;
    font-size: 13px;
}

.return-message .el-dialog__header {
    border-bottom: 1px solid #e4e7ec;
    padding: 10px;
}

.return-message .el-dialog__footer {
    padding: 5px 20px 10px;
    border-top: 1px solid #e4e7ec;
}

.return-message .el-dialog__body .el-form-item {
    margin-bottom: 15px
}

.return-message .el-dialog__headerbtn {
    top: 14px;
    right: 10px;
    height: fit-content;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.interface-log-switch {
    width: 100% !important;

    .el-switch__core {
        width: 100% !important;
    }
}
</style>
